package com.jochen.core.audio;

import com.badlogic.gdx.audio.Music
import com.badlogic.gdx.math.MathUtils
import com.jochen.core.assets.AssetService
import com.jochen.core.assets.MusicAsset
import com.jochen.core.assets.SoundAsset

class AudioService(private val assetService: AssetService){

    private var curMusic: Music? = null
    private var curMusicAsset: MusicAsset? = null
    
    var musicVolume: Float = 0.5f
        set(value){
            field = MathUtils.clamp(value, 0f, 1f)
            this.curMusic?.volume = field
        }
    var soundVolume: Float = 0.33f 
        set(value){
            field = MathUtils.clamp(value, 0f, 1f)
        } 
        
    fun playMusic(asset: MusicAsset){
        if(curMusicAsset == asset) return
        
        curMusic?.let{
            it.stop()
            curMusicAsset?.let{ musicAsset ->
                assetService.unload(musicAsset)
            }
        }
        
        curMusic = assetService.load(asset).apply{
            isLooping = true
            volume = musicVolume
            play()
        }
        curMusicAsset = asset
    }  
    
    fun stopMusic(): MusicAsset?{
        curMusic?.let{
            it.stop()
            curMusicAsset?.let{ musicAsset ->
                assetService.unload(musicAsset)
            }
        }
        val music = curMusicAsset
        curMusicAsset = null
        curMusic = null
        return music
    }
    
    fun playSound(asset: SoundAsset){
        assetService.get(asset).play(soundVolume)
    }
}